<template>
  <el-dialog title="新增变量" v-model="isAdd" width="30%">
    <el-form
      :model="newVariable"
      ref="addVariableForm"
      label-width="80px"
      :inline="false"
      size="default"
    >
      <el-form-item label="变量名">
        <el-input v-model="newVariable.varName"></el-input>
      </el-form-item>

      <el-form-item label="变量值">
        <el-input v-model="newVariable.varValue"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span>
        <el-button @click="isAdd = false">取消</el-button>
        <el-button type="primary" @click="addVariable">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <el-card
    shadow="always"
    :body-style="{
      padding: '20px',
      height: 'calc(calc(100vh - 170px) / 2 - 68px)',
    }"
  >
    <template #header>
      <el-row>
        <el-col :span="12"
          ><span style="font-size: larger; font-weight: bold"
            >【{{ projectStore.selectedProject.name }}】中的变量信息</span
          ></el-col
        >
        <el-col :span="12" style="text-align: right">
          <el-button
            type="success"
            size="default"
            @click="isAdd = true"
            :disabled="projectStore.selectedProject.id === -1"
          >
            <el-icon><Plus /></el-icon> 新增变量</el-button
          ></el-col
        >
      </el-row>
    </template>
    <vxe-table
      ref="variableTable"
      keep-source
      border
      show-overflow
      height="100%"
      :column-config="{ resizable: true }"
      :data="sunnyVariablelist"
      :edit-config="{ trigger: 'manual', mode: 'row' }"
    >
      <vxe-column type="seq" width="60"></vxe-column>
      <vxe-column
        field="varName"
        title="参数名"
        :edit-render="{ autofocus: '.vxe-input--inner' }"
      >
        <template #edit="{ row }">
          <vxe-input
            v-model="row.varName"
            type="text"
            @blur="noticeNotSave"
          ></vxe-input>
        </template>
      </vxe-column>
      <vxe-column
        field="varValue"
        title="参数值"
        :edit-render="{ autofocus: '.vxe-input--inner' }"
      >
        <template #edit="{ row }">
          <vxe-input
            v-model="row.varValue"
            type="text"
            @blur="noticeNotSave"
          ></vxe-input>
        </template>
      </vxe-column>
      <vxe-column title="操作">
        <template #default="{ row }">
          <template v-if="!isRowEdit(row)">
            <el-button
              type="primary"
              :icon="EditPen"
              @click="editVariables(row)"
            ></el-button>
            <el-button
              type="danger"
              :icon="Delete"
              @click="deleteVariable(row)"
            >
            </el-button>
          </template>
          <template v-else>
            <el-button
              type="success"
              :icon="Check"
              @click="saveEdit(row)"
            ></el-button>
            <el-button
              type="danger"
              :icon="Close"
              @click="cancelEdit(row)"
            ></el-button>
          </template>
        </template>
      </vxe-column>
    </vxe-table>
  </el-card>
</template>

<script setup lang="ts">
import { useProjectStore } from "@/stores/sunnyProjectStore";
import { EditPen, Check, Close, Delete, Plus } from "@element-plus/icons-vue";
import {
  listVariablesApi,
  deleteVariablesApi,
  addVariablepi,
  updateVariablesApi,
} from "@/api/sunnyvariable";
import type { SunnyVariable } from "@/types/sunnyVariable/type";
import { ref, onMounted, computed } from "vue";
import { onBeforeRouteUpdate } from "vue-router";
import type { VxeTableInstance } from "vxe-table";
import { ElMessage } from "element-plus";

const props = defineProps<{ projectId: string }>();

const projectStore = useProjectStore();

const sunnyVariablelist = ref<SunnyVariable[]>([]);

const variableTable = ref<VxeTableInstance>();

const isAdd = ref(false);

const newVariable = ref<SunnyVariable>({
  id: 0,
  projectId: 0,
  varName: "",
  varValue: "",
});

onMounted(() => {
  listVariables();
});

onBeforeRouteUpdate(() => {
  listVariables();
});

function listVariables() {
  listVariablesApi(projectStore.selectedProject.id).then(({ data }) => {
    sunnyVariablelist.value = data;
  });
}

function isRowEdit(row: SunnyVariable): boolean {
  if (variableTable.value) {
    //判断一行是否正在编辑状态。
    return variableTable.value.isEditByRow(row);
  }
  return false;
}

/**新增变量 */
function addVariable() {
  isAdd.value = false;
  //判断当前的变量列表中是否有重复的变量名
  let existVar = sunnyVariablelist.value.find(
    (variable) => variable.varName === newVariable.value.varName
  );
  //如果已经有同名变量了，不允许提交
  if (existVar) {
    ElMessage.error("已经有同名的变量了，不允许再次新增同名变量。");
  } else {
    newVariable.value.projectId = projectStore.selectedProject.id;
    addVariablepi(newVariable.value).then(() => {
      ElMessage.success(
        `新增变量${newVariable.value.varName}：${newVariable.value.varValue}成功`
      );
      listVariables();
    });
  }
}

function editVariables(row: SunnyVariable) {
  //开启编辑状态
  variableTable.value?.setEditRow(row);
}

function saveEdit(row: SunnyVariable) {
  //要判断列表中是否有超过1个同名的变量
  if (
    sunnyVariablelist.value.filter(
      (variable) => variable.varName === row.varName
    ).length > 1
  ) {
    ElMessage.error(`已经有同名的${row.varName}变量了，不允许再次新增。`);
    cancelEdit(row);
  } else {
    variableTable.value?.clearEdit().then(() => {
      updateVariablesApi(row)
        .then(() => {
          ElMessage.success(`修改变量${row.varName}:${row.varValue}成功`);
        })
        .then(() => {
          listVariables();
        });
    });
  }
}

function cancelEdit(row: SunnyVariable) {
  //关闭编辑状态
  variableTable.value?.clearEdit().then(() => {
    //恢复修改之前的数据
    variableTable.value?.revertData(row);
  });
}

function deleteVariable(row: SunnyVariable) {
  deleteVariablesApi(row.id).then(() => {
    ElMessage.success(`删除变量${row.varName}:${row.varValue}成功`);
    listVariables();
  });
}

function noticeNotSave() {
  ElMessage.info("修改并未真正生效，如果要提交变量修改，请点击保存按钮。");
}
</script>

<style scoped>
.el-card {
  margin-top: 15px;
}
</style>
